package com.github.xaidanwang.auth.server.auth;


import com.github.xaidanwang.auth.server.biz.UserBiz;
import com.github.xaidanwang.auth.server.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * @author wang yi fei
 * @date 2019/10/4 10:44
 */
@Slf4j
@Service("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
	@Autowired
	protected PasswordEncoder passwordEncoder;
	@Autowired
	protected UserBiz userBiz;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		UserInfo userInfo = userBiz.getUserInfoByUserName(username);
		if (userInfo == null){
			throw new UsernameNotFoundException("该账号不存在");
		}
		log.info("加密后的密码"+ userInfo.getPassword());
		log.info("加密后的用户名称"+ passwordEncoder.encode(username));
		User user = new User(username,passwordEncoder.encode(userInfo.getPassword()),obtainGrantedAuthorities(userInfo));
		return user;
	}

	/**
	 * 获得登录者所有角色的权限集合.
	 * @param
	 * @return
	 */
	protected Set<GrantedAuthority> obtainGrantedAuthorities(UserInfo userInfo) {
		SimpleGrantedAuthority simpleGrantedAuthority;
		Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
		if (userInfo.getUsername().equalsIgnoreCase("admin")){
			simpleGrantedAuthority = new SimpleGrantedAuthority("admin");
		}else {
			simpleGrantedAuthority = new SimpleGrantedAuthority("user");
		}
		grantedAuthorities.add(simpleGrantedAuthority);
		return grantedAuthorities;
	}
}
